﻿import 'dart:async';
import 'package:azring/core/repository/default_api.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/common/langs/text_key.dart';
import 'package:azring/common/res/gaps.dart';
import 'package:azring/common/utils/change_notifier_manage.dart';
import 'package:azring/common/utils/keyboard_util.dart';
import 'package:azring/entity/sendcode_entity.dart';
import 'package:azring/widget/my_scroll_view.dart';

import '../login/login_logic.dart';

/// design/1注册登录/index.html#artboard4
class SMSLoginView extends StatefulWidget {
  final VoidCallback? onSwitchToPasswordLogin;

  const SMSLoginView({super.key, this.onSwitchToPasswordLogin});

  @override
  _SMSLoginViewState createState() => _SMSLoginViewState();
}

class _SMSLoginViewState extends State<SMSLoginView>
    with ChangeNotifierMixin<SMSLoginView> {
  final LoginLogic logic = Get.put(LoginLogic());
  final TextEditingController _phoneLogic = TextEditingController();
  final TextEditingController _vCodeLogic = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();

  bool _clickable = false;
  bool _agreeTerms = false;
  String? _sendUUID;
  static const _phoneAreaChina = '+86';
  String _phoneArea = _phoneAreaChina;

  // 验证码倒计时相关状态 - 使用GetX响应式变量
  Timer? _countdownTimer;
  final RxInt _countdownSeconds = 0.obs;
  final RxBool _isCountdownActive = false.obs;
  final RxBool _canSendCode = false.obs;

  @override
  void initState() {
    super.initState();
    // 添加焦点监听器
    _nodeText1.addListener(_onFocusChange1);
    _nodeText2.addListener(_onFocusChange2);
  }

  void _onFocusChange1() {
    if (mounted) {
      setState(() {});
    }
  }

  void _onFocusChange2() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void dispose() {
    _nodeText1.removeListener(_onFocusChange1);
    _nodeText2.removeListener(_onFocusChange2);
    _countdownTimer?.cancel();
    super.dispose();
  }

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _phoneLogic: callbacks,
      _vCodeLogic: callbacks,
      _nodeText1: null,
      _nodeText2: null,
    };
  }

  void _verify() {
    final String phone = _phoneLogic.text;
    final String vCode = _vCodeLogic.text;
    bool clickable = true;
    if (phone.isEmpty || phone.length < 11) {
      clickable = false;
    }
    if (vCode.isEmpty || vCode.length < 6) {
      clickable = false;
    }
    if (!_agreeTerms) {
      clickable = false;
    }

    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }

    // 检查是否可以发送验证码
    bool canSend = _isValidPhone(phone) && !_isCountdownActive.value;
    if (canSend != _canSendCode.value) {
      _canSendCode.value = canSend;
    }
  }

  // 验证手机号格式
  bool _isValidPhone(String phone) {
    if (phone.isEmpty) return false;
    // 手机号验证（11位数字）
    return RegExp(r'^1[3-9]\d{9}$').hasMatch(phone);
  }

  // 开始倒计时
  void _startCountdown() {
    _countdownSeconds.value = 50;
    _isCountdownActive.value = true;
    _canSendCode.value = false;

    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_countdownSeconds.value > 0) {
        _countdownSeconds.value--;
      } else {
        _stopCountdown();
      }
    });
  }

  // 停止倒计时
  void _stopCountdown() {
    _countdownTimer?.cancel();
    _countdownTimer = null;
    _isCountdownActive.value = false;
    _countdownSeconds.value = 0;
    _verify(); // 重新检查是否可以发送验证码
  }

  // 发送验证码
  Future<void> _sendVerificationCode() async {
    if (!_canSendCode.value) return;

    try {
      dynamic response = await DefaultApi()
          .sendSmsChinaGet(phone: _phoneLogic.text.toString());

      if (response != null) {
        _sendUUID = response['uuid'];
        _startCountdown();
        Toast.show('验证码发送成功');
      }
    } catch (e) {
      print(e);
      Toast.show('验证码发送失败，请重试');
    }
  }

  void _login() {
    logic.requestData(
        username: _phoneLogic.text.toString(),
        uuid: _sendUUID,
        code: _vCodeLogic.text.toString());
  }

  @override
  Widget build(BuildContext context) {
    return MyScrollView(
      keyboardConfig: KeyboardUtil.getKeyboardActionsConfig(
          context, <FocusNode>[_nodeText1, _nodeText2]),
      children: _buildBody(),
    );
  }

  List<Widget> _buildBody() {
    return <Widget>[
      Gaps.vGap21,

      // 手机号输入框
      _buildPhoneInput(),
      Gaps.vGap18,

      // 验证码输入框
      _buildVCodeInput(),
      Gaps.vGap21,

      // 按钮区域
      _buildButtonSection(),
      Gaps.vGap35,

      // 同意条款
      _buildTermsSection(),
      SizedBox(height: 140.h),

      // 登录按钮
      _buildLoginButton(),
    ];
  }

  // 构建手机号输入框
  Widget _buildPhoneInput() {
    return Container(
      height: 56.h,
      decoration: BoxDecoration(
        color: const Color(0xFF282528),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: _nodeText1.hasFocus
              ? const Color(0xffF45757)
              : Colors.transparent,
          width: 0.5.w,
        ),
      ),
      child: TextField(
        focusNode: _nodeText1,
        controller: _phoneLogic,
        style: const TextStyle(color: Colors.white, fontSize: 14),
        keyboardType: TextInputType.phone,
        textAlignVertical: TextAlignVertical.center,
        onTap: () {
          setState(() {
            // 确保焦点变化时更新UI
          });
        },
        decoration: const InputDecoration(
          hintText: "请输入手机号",
          hintStyle: TextStyle(color: Colors.white, fontSize: 14),
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(horizontal: 25, vertical: 18),
        ),
      ),
    );
  }

  // 构建验证码输入框
  Widget _buildVCodeInput() {
    return Container(
      height: 56.h,
      decoration: BoxDecoration(
        color: const Color(0xFF282528),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: _nodeText2.hasFocus
              ? const Color(0xffF46425)
              : Colors.transparent,
          width: 0.5.w,
        ),
      ),
      child: TextField(
        focusNode: _nodeText2,
        controller: _vCodeLogic,
        style: const TextStyle(color: Colors.white, fontSize: 14),
        keyboardType: TextInputType.number,
        textAlignVertical: TextAlignVertical.center,
        onTap: () {
          setState(() {
            // 确保焦点变化时更新UI
          });
        },
        decoration: InputDecoration(
          hintText: "请输入验证码",
          hintStyle: const TextStyle(color: Colors.white, fontSize: 14),
          border: InputBorder.none,
          contentPadding:
              const EdgeInsets.symmetric(horizontal: 25, vertical: 18),
          suffixIcon: Obx(() => GestureDetector(
                onTap: _canSendCode.value ? _sendVerificationCode : null,
                child: Container(
                  margin: const EdgeInsets.all(8),
                  padding:
                      const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  child: Text(
                    _isCountdownActive.value
                        ? "${_countdownSeconds.value}秒后重发"
                        : "获取手机验证码",
                    style: TextStyle(
                      color: _canSendCode.value
                          ? const Color(0xffF46425)
                          : const Color(0xffF46425).withOpacity(0.65),
                      fontSize: 12.sp,
                    ),
                  ),
                ),
              )),
        ),
      ),
    );
  }

  // 构建按钮区域
  Widget _buildButtonSection() {
    return Row(
      children: [
        const Spacer(),
        GestureDetector(
          onTap: () {
            // 处理获取不到验证码
          },
          child: Container(
            width: 120.w,
            height: 32.h,
            decoration: BoxDecoration(
              border: Border.all(color: const Color(0xffF46425)),
              borderRadius: BorderRadius.circular(18.r),
            ),
            child: Center(
              child: Text(
                "获取不到验证码",
                style: TextStyle(
                  color: Color(0xffF46425),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w300,
                ),
              ),
            ),
          ),
        ),
        Gaps.hGap10,
        GestureDetector(
          onTap: () {
            widget.onSwitchToPasswordLogin?.call();
          },
          child: Container(
            width: 80.w,
            height: 32.h,
            decoration: BoxDecoration(
              color: const Color(0xffF46425).withOpacity(0.9),
              borderRadius: BorderRadius.circular(18),
            ),
            child: Center(
              child: Text(
                "密码登录",
                style: TextStyle(
                  color: Colors.white.withOpacity(0.65),
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w300,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建同意条款区域
  Widget _buildTermsSection() {
    return Row(
      children: [
        Gaps.hGap16,
        GestureDetector(
          onTap: () {
            setState(() {
              _agreeTerms = !_agreeTerms;
              _verify();
            });
          },
          child: Container(
            width: 14.w,
            height: 14.h,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: _agreeTerms ? const Color(0xffF46425) : Colors.transparent,
              border: Border.all(
                color: _agreeTerms
                    ? const Color(0xffF46425)
                    : const Color(0xFF666666),
                width: 1,
              ),
            ),
            child: _agreeTerms
                ? const Icon(
                    Icons.check,
                    color: Colors.white,
                    size: 14,
                  )
                : null,
          ),
        ),
        Gaps.hGap8,
        Expanded(
            child: RichText(
          text: TextSpan(
            children: [
              TextSpan(
                text: TextKey.agreeTerms.tr, // "我已阅读并同意"
                style: TextStyle(color: Colors.white),
              ),
              TextSpan(
                text: TextKey.terms.tr, // "使用条款"
                style: TextStyle(color: Color(0xffF46425)),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    // 处理使用条款点击
                  },
              ),
              TextSpan(
                text: TextKey.and.tr, // "和"
                style: TextStyle(color: Colors.white),
              ),
              TextSpan(
                text: TextKey.privacy.tr, // "隐私政策"
                style: const TextStyle(color: Color(0xffF46425)),
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    // 处理隐私政策点击
                  },
              ),
            ],
          ),
        )),
      ],
    );
  }

  // 构建登录按钮
  Widget _buildLoginButton() {
    return Container(
      width: double.infinity,
      height: 56.h,
      decoration: BoxDecoration(
        color: _clickable
            ? const Color(0xffF46425)
            : const Color(0xffF46425).withOpacity(0.5),
        borderRadius: BorderRadius.circular(999.r),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: _clickable ? _login : null,
          borderRadius: BorderRadius.circular(999.r),
          child: Center(
            child: Text(
              TextKey.loginButton.tr,
              style: TextStyle(
                color:
                    _clickable ? Colors.white : Colors.white.withOpacity(0.5),
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
